package com.vizhuo.push.umeng.base;

import com.vizhuo.client.business.appmanage.vo.AndroidPushCustomMessage;
import com.vizhuo.push.umeng.android.AndroidPayload;
import com.vizhuo.push.umeng.android.AndroidPayloadBody;
import com.vizhuo.push.umeng.android.AndroidSendRequest;
import com.vizhuo.push.umeng.ios.IOSSendRequest;
import com.vizhuo.push.util.JacksonUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @author YuanWenLong 作者 E-mail: yuanwenlong2010@163.com
 * @date 创建时间：2015年7月8日 上午11:14:30
 * @version 1.0
 * @parameter
 * @since
 * @return
 */
public class PushClient {
    private static Logger logger = LoggerFactory.getLogger(PushClient.class);

    // This object is used for sending the post request to Umeng
    private static HttpClient client;

    private final String host = "http://msg.umeng.com";

    // The upload path
    private final String uploadPath = "/upload";

    // The post path
    private final String postPath = "/api/send";

    private String USER_AGENT = "Mozilla/5.0";

    private int appType;

    private String appMasterSecret;

    private String appkey;
    //默认是测试环境，android不用区分都可以接收
    private String productionMode;

    public PushClient(String appMasterSecret, String appkey) {
        this.appMasterSecret = appMasterSecret;
        this.appkey = appkey;
    }

    public PushClient() {
    }

    public PushResult send(AndroidSendRequest req) throws Exception {
        req.setAppkey(appkey);
        String checkResult = req.checkParameter();
        // checkResult = null;
        String postBody = JacksonUtil.toJson(req);
        PushResult sendResult = null;
        if (StringUtils.isNotEmpty(checkResult)) {
            sendResult = new PushResult();
            sendResult.setRet(PushConstant.RET_SYSTEM_FAIL);
            sendResult.setSysError(checkResult);
            sendResult.setRequestJSON(postBody);
            return sendResult;
        } else {
            if (client == null) {
                client = getHttpClient();
            }
            String url = host + postPath;
            logger.info("Android send :" + postBody);
            String sign = DigestUtils.md5Hex(("POST" + url + postBody + appMasterSecret).getBytes("utf8"));
            url = url + "?sign=" + sign;
            HttpPost post = new HttpPost(url);
            post.setHeader("User-Agent", USER_AGENT);
            StringEntity se = new StringEntity(postBody, "UTF-8");
            post.setEntity(se);
            HttpResponse response = client.execute(post);
            int status = response.getStatusLine().getStatusCode();
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }

            sendResult = JacksonUtil.toObject(result.toString(), PushResult.class);
            sendResult.setHttpResult(status);
            sendResult.setReturnJSON(result.toString());
            sendResult.setRequestJSON(postBody);

            return sendResult;
        }

    }

    public PushResult send(IOSSendRequest req) throws Exception {
        req.setAppkey(appkey);
        String checkResult = req.checkParameter();
        // checkResult = null;
        PushResult sendResult = null;
        String postBody = JacksonUtil.toJson(req);
        if (StringUtils.isNotEmpty(checkResult)) {
            sendResult = new PushResult();
            sendResult.setRet(PushConstant.RET_SYSTEM_FAIL);
            sendResult.setSysError(checkResult);
            sendResult.setRequestJSON(postBody);
            return sendResult;
        } else {
            if (client == null) {
                client = getHttpClient();
            }
            String url = host + postPath;
            logger.info("IOS send :" + postBody);
            String sign = DigestUtils.md5Hex(("POST" + url + postBody + appMasterSecret).getBytes("utf8"));
            url = url + "?sign=" + sign;
            HttpPost post = new HttpPost(url);
            post.setHeader("User-Agent", USER_AGENT);
            StringEntity se = new StringEntity(postBody, "UTF-8");
            post.setEntity(se);
            HttpResponse response = client.execute(post);
            int status = response.getStatusLine().getStatusCode();
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }

            sendResult = JacksonUtil.toObject(result.toString(), PushResult.class);
            sendResult.setHttpResult(status);
            sendResult.setReturnJSON(result.toString());
            sendResult.setRequestJSON(postBody);
            return sendResult;
        }

    }

    public String getAppMasterSecret() {
        return appMasterSecret;
    }

    public void setAppMasterSecret(String appMasterSecret) {
        this.appMasterSecret = appMasterSecret;
    }

    public String getHost() {
        return host;
    }

    public String getUploadPath() {
        return uploadPath;
    }

    public String getPostPath() {
        return postPath;
    }

    public String getProductionMode() {
        return productionMode;
    }

    public void setProductionMode(String productionMode) {
        this.productionMode = productionMode;
    }

    public static DefaultHttpClient getHttpClient() {
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
        HttpProtocolParams.setUseExpectContinue(params, true);
        int REQUEST_TIMEOUT = 10 * 1000;
        int SO_TIMEOUT = 10 * 1000;
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, REQUEST_TIMEOUT);
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);
        SchemeRegistry schreg = new SchemeRegistry();
        schreg.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        schreg.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
        PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(schreg);
        pccm.setDefaultMaxPerRoute(20);
        pccm.setMaxTotal(100);
        DefaultHttpClient httpClient = new DefaultHttpClient(pccm, params);
        return httpClient;
    }

    public static void main(String[] args) {
        AndroidSendRequest req = new AndroidSendRequest();
        req.setType(PushConstant.TYPE_UNICAST);
        // req.setDevice_tokens("AiQ0GPhi_JPqFPKsdXkRumZZoRsWpoUbv6AT2QnHiKDc");
        req.setDevice_tokens("Aqi6T3DWXjRcBzHlnSwcK-VUIW75z0oXx4_kyfnaK45V");
        AndroidPayload payLoad = new AndroidPayload();
        payLoad.setDisplay_type(PushConstant.DISPLAY_TYPE_MESSAGE);
        AndroidPayloadBody body = new AndroidPayloadBody();
        body.setTitle("测试推送Title13");
        body.setTicker("测试推送Ticker14");
        body.setText("测试推送Text12");
        body.setCustom(new AndroidPushCustomMessage());
        body.setAfter_open(PushConstant.AFTER_OPEN_GO_CUSTOM);
        payLoad.setBody(body);
        req.setPayload(payLoad);

        PushClient client = new PushClient("nnyfq4x5tqefddt5r8ycuixqquz5ipo8", "559c890467e58e4a6f005b41");
        try {
            PushResult sendResult = client.send(req);
            System.out.println(sendResult.getReturnJSON());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public String getAppkey() {
        return appkey;
    }

    public void setAppkey(String appkey) {
        this.appkey = appkey;
    }

    public int getAppType() {
        return appType;
    }

    public void setAppType(int appType) {
        this.appType = appType;
    }

}
